<?php
namespace app\admin\controller;

use app\common\business\Category as CategoryBus;
use app\common\lib\Status as StatusLib;
use think\facade\View;

class Category extends AdminBase {

    public function index() {
        $pid  = input('param.pid', 0, 'intval');
        $data = [
            'pid' => $pid,
        ];

        try {
            $categorys = (new CategoryBus())->getLists($data, 5);
        } catch (\Exception $e) {
            $categorys = \app\common\lib\Arr::getPaginateDefaultData(5);
        }

        return View::fetch("", [
            "categorys" => $categorys,
            "pid"       => $pid,
        ]);
    }

    public function add() {

        try {
            $categorys = (new CategoryBus())->getNormalCategorys();
        } catch (\Exception $e) {
            $categorys = [];
        }

        return View::fetch("", [
            //"categorys" => $categorys,
            "categorys" => json_encode($categorys),
        ]);
    }

    public function save() {

        $pid  = input('param.pid', 0, 'intval');
        $name = input('param.name', '', 'trim');

        $data = [
            'pid'  => $pid,
            'name' => $name,
        ];

        $validate = new \app\admin\validate\Category();
        if (!$validate->check($data)) {
            return show(config('status.error'), $validate->getError());
        }

        try {
            $result = (new CategoryBus())->add($data);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }

        if ($result) {
            return show(config("status.success"), "OK");
        }
        return show(config("status.error"), "新增分类失败");

    }

    /**
     * 提前准备好的代码， 9-3节内容，带小伙伴过下代码。
     * @return \think\response\View
     */
    public function dialog() {
        // 获取正常的一级分类数据。 代码提供好 带小伙伴解读下代码 @9-5
        $categorys = (new CategoryBus())->getNormalByPid();
        return view("", [
            "categorys" => json_encode($categorys),
        ]);
    }

    /**
     * 提前准备好的代码， 9-5节内容，带小伙伴过下代码。
     * @return \think\response\Json
     */
    public function getByPid() {
        $pid       = input("param.pid", 0, "intval");
        $categorys = (new CategoryBus())->getNormalByPid($pid);
        return show(config("status.success"), "OK", $categorys);
    }

}